package com.escope.casemanager.controller;

import com.escope.casemanager.model.CaseShare;
import com.escope.casemanager.service.CaseShareService;
import com.escope.casemanager.uti.DateUtil;
import com.escope.casemanager.uti.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("share")
@CrossOrigin
public class ServerProxyController {

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${escope.project.file-path}")
    private String projectPath;


    @Autowired
    private CaseShareService caseShareService;

    @Autowired
    private RedisUtil redisUtil;


    @RequestMapping(value = "/**")
    public ResponseEntity<Resource> access(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String requestURI = request.getRequestURI();
        String  param = requestURI.substring((contextPath+"/share/").length());

        //去除 ?或# 相关内容
        System.out.println(param);
        int i1 = param.indexOf("?");
        int i2 = param.indexOf("#");
        int last = param.length();
        if(i1 > 0 && i2 > 0){
            last = i1;
            if(i2 < last){
                last = i2;
            }
        }else{
           if(i1 > 0){
               last = i1;
           }
           if(i2 > 0){
               last = i2;
           }
        }

        param = param.substring(0, last);
        String[] paths = param.split("/");
        if(paths.length >0){
            String token = paths[0];
            // 判断是否存在该分享
            CaseShare share = null;//redisUtil.getShareCacheInfo(token);
            if(share == null){
                share = caseShareService.findByToken(token);
                if(share == null || DateUtil.getCurTime().getTime().compareTo(share.getExpireDate()) > 0){
                    sendError(response);
                    return null;
                }else {
                    redisUtil.setShareCacheInfo(share);
                }
            }

            // 获取请求资源并返回给客户端
            Path pp = Paths.get(projectPath).toAbsolutePath().normalize();
            pp = pp.resolve(share.getDirName());
            String fileName = "";

            if(paths.length > 1){
                for(int i = 1; i < paths.length; i++){
                    pp = pp.resolve(paths[i]); // 将url中的路径信息拼接到 物理文件路径中
                }
                fileName = paths[paths.length-1];
            }
            Resource resource = new UrlResource(pp.toUri());
            if (resource.exists()) {
                String contentType = request.getServletContext().getMimeType(fileName);
                if(StringUtils.isEmpty(contentType)){
                    contentType = "application/octet-stream";
                }
                return ResponseEntity.ok().contentType(MediaType.valueOf(contentType)).body(resource);
            } else {
                sendError(response);
                return null;
            }
        }else{
            sendError(response);
            return null;
        }
    }

    public void sendError(HttpServletResponse response) throws IOException {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
    }

}
